#include "Ulti.h"
#include "BitmapCharacterSet.h"
#include "GlobalVar.h"
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>

void log2file(char *format, ...) {
	va_list ptr; /* get an arg pointer */
 	FILE *fp = fopen("log.txt", "at");
	if (fp) {
		/* initialize ptr to point to the first argument after the format string */
		va_start(ptr, format); 
		/* Write to logfile. */
		vfprintf(fp, format, ptr); // Write passed text. 
		va_end(ptr); 
		fclose(fp);
	}
}

// read intput file and store it at ascii string in DATA
// return data length
unsigned int readInput(char* fName)
{
	FILE *ifp = fopen(fName,"r");
	if(!ifp)
	{
		log2file("Cant open file %s\n",fName);
		exit(1);
	}
	unsigned int i=0;
	for(char c;(c=fgetc(ifp))!=EOF;DATA[i++]=c);
	fclose(ifp);
	return i;
}

//get the pos of the last char of the next word matching
//next char is the continous char
//return EOF if no next word matching
int findOnward(char* word,FILE* fp)
{
	char c;
	for(;;)
	{
		while((c=fgetc(fp))!=EOF && c!=*word);
		if(c==*word)
		{
			char* s=word;
			for(;*++s && (c=fgetc(fp))!=EOF && *s==c;);			
			if(*s == 0) return ftell(fp);
		}
		if(c==EOF) break;
	}
	return EOF;
}

// get the next value after the string
// assign it to d
void getNextAtribute(char* word,FILE* fp,unsigned int &d)
{
	findOnward(word,fp);
	fscanf(fp,"%d",&d);
}

// get the next BYTE value after the string
void getNextBYTEAtribute(char* word,FILE* fp,BYTE &b)
{
	unsigned int d;
	findOnward(word,fp);
	fscanf(fp,"%d",&d);
	b=d;
}

// get the path in "path" format
void getNextPath(char* word,FILE* fp,char *s)
{
	findOnward(word,fp);
	findOnward("\"",fp);
	for(;(*s=fgetc(fp))!='"';s++);
	*s=0;
}